{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import math"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 5,  6,  8, 11, 15, 20, 26, 33, 41, 41, 41, 41, 41, 41, 41, 41])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.tensor([5, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0]) # input array\n",
    "L = X.size(0)\n",
    "\n",
    "Xa = X \n",
    "num_steps = int(math.log2(L))\n",
    "\n",
    "for k in range(num_steps):\n",
    "    T = 2 * (Xa.size(0) // 2)\n",
    "\n",
    "    # split into 2 groups of pairs of elements\n",
    "    Xa = Xa.view(T//2, 2) \n",
    "\n",
    "    # for each pair, add the first to the second\n",
    "    Xa[:, 1].add_(Xa[:, 0])\n",
    "\n",
    "    # change the view for the next iteration\n",
    "    Xa = Xa[:, 1]\n",
    "\n",
    "# down sweep\n",
    "for k in range(num_steps-1, -1, -1):\n",
    "    Xa = X[2**k-1:L:2**k]\n",
    "\n",
    "    T = 2 * (Xa.size(0) // 2)\n",
    "\n",
    "    if T < Xa.size(0):\n",
    "        Xa[:, :, -1].add_(Xa[:, :, -2])\n",
    "\n",
    "    Xa = Xa[:T].view(T//2, 2)\n",
    "\n",
    "    Xa[1:, 0].add_(Xa[:-1, 1])\n",
    "\n",
    "X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch23",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.1.undefined"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
